package com.health.mapp.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.health.db.dto.StuffDetailDto;
import com.health.db.model.GoodsPriceList;
import com.health.db.model.GoodsPriceListTemp;
import com.health.db.model.MedicalTreatRecordTemp;
import com.health.db.model.MedicalTreatRecordWithBLOBs;
import com.health.db.model.PatientList;
import com.health.db.model.PatientListTemp;
import com.health.db.model.RegisterOrder;
import com.health.db.model.RegisterOrderExample;
import com.health.db.model.RegisterOrderTemp;
import com.health.db.model.UserLIST;
import com.health.db.service.order.IRegisterOrderService;
import com.health.db.service.sm.IRongService;
import com.health.db.service.user.IGoodsPriceListService;
import com.health.db.service.user.IPatientListService;
import com.health.db.service.user.IStuffListService;
import com.health.db.service.user.IUserLISTService;
import com.health.mapp.bean.GeneratePreOrderReq;
import com.health.mapp.bean.GeneratePreOrderResp;
import com.health.mapp.bean.Header;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.DateUtils;
import com.health.mapp.utils.JudeMobileAttribution;
import com.health.mapp.utils.Response;
import com.health.mapp.utils.ResultCode;

/**
 *  预订单生成查询类
 *  首儿送药
 * @author HiRoad
 * 
 * @pramati
 * 	private Long patId;//	String(Long)	Y	就诊人ID
	private Long userId	;//String(Long)	Y	用Id
	private int orderType;//	Int 	Y	订单类型 1:图文咨询 2:电话咨询 3:视频咨询 4：首尔送药
	private int freeType;//	Int	Y	是否免费咨询，默认为是。0：是 ；1：否
	private String goodsId	;//	String N	非免费咨询的时候必传
	private int channel	;//Int	Y	来源渠道
	private String contactTel	;//String	N	联系电话
	private String scheduleTime	;//String(Time)	N	预约时间，免费咨询传空或默认值2017-02-21 13:00 
	private String scheduleDate;//	String(Time)	N	预约时间，免费咨询传空或默认值2017-02-21
	private int orderTimeSolt ;//	Int	N	时间节点
	private String orderTime	;//String(Time)	N	预订时间长，免费咨询传空或默认值
	private Long treatDocId;//	Long	N	就诊医师ID，免费咨询传空或默认值
	private String treatDocName;//	String	N	就诊医师姓名，免费咨询传空或默认值
	private String departmentName	;//String	N	科室名称，免费咨询传空或默认值
	private int departmentId;//	int	N	科室ID，免费咨询传空或默认值
	private int hospitalId;//	Int	Y	医院编号，默认为2
	private int patInsertMode	;//Int	N	病人自述插入方式空或者0：
	private String patRecord ;//未预先生成，需要插入patRecord对象   //1：patRecord已经预先生成，只需要插入实现生成的patRecordId
	private String patRecordId	;//Int	N	patInsertMode=1，必传
	private String patDescribe	;//String	N	病人自述  patInsertMode=0或者空，必传
	private String patPage1	;//String,File	N	病人上传图片路径，文件上传
	private String patPage2	;//String,File	N	病人上传图片路径，文件上传
	private String patPage3	;//String,File	N	病人上传图片路径，文件上传
	private String patPage4	;//String,File	N	病人上传图片路径，文件上传
	private String patPage5	;//String,File	N	病人上传图片路径，文件上传
	private String patPage6	;//String,File	N	病人上传图片路径，文件上传
 *
 */
public class GeneratePreOrderImpl implements ActionInterface {
	
	//service import
	private IRegisterOrderService registerOrderService  ;
	private IUserLISTService userLISTService  ;
	private IPatientListService patientListService  ;
	private IGoodsPriceListService goodsPriceListService  ;
	private IRongService rongService  ; 
	private IStuffListService stuffListService;
	
	
	
	@Override
	public Response execute(Header header, Object reqBean) throws Exception {
		
		GeneratePreOrderReq req = (GeneratePreOrderReq) reqBean; 
		GeneratePreOrderResp _resp = new GeneratePreOrderResp();
		Long userId = req.getUserId();
		Long patientId=req.getPatId();
		int freeType=req.getFreeType();
		if (userId==0||req.getOrderType()==0||req.getChannel()==0) {
			_resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
			_resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);
			return _resp;
		}
		else
		{
			//RegisterOrder 包装
			RegisterOrder orderInfo = new RegisterOrder();
			
			//记录appid
			orderInfo.setWorkFlowStatus(header.getAppId());
			
			orderInfo.setRegisterguideid(String.valueOf(req.getChannel()));
			orderInfo.setRegisterNo(DateUtils.todayDate()+"-H"+req.getHospitalId()+"U"+userId+"-");
			orderInfo.setPatientid(patientId);
			orderInfo.setUserid(userId);
			orderInfo.setRegisterDesc(req.getPatDescribe());
			orderInfo.setEntityid(req.getHospitalId());
			orderInfo.setRegistertypeid(req.getOrderType());
			orderInfo.setRegisterTypeName(Constant.CONSTANTS_ORDER_TYPE_Map.get(req.getOrderType()));
			orderInfo.setUpdateUserid(userId);
			orderInfo.setOrderfeetypeid(freeType);
			orderInfo.setOrderTypeDesc(Constant.CONSTANTS_ORDER_TYPE_Map.get(req.getOrderType())+","+Constant.CONSTANTS_ORDER_FREE_Map.get(freeType));

			//查看用户表相关信息
			UserLIST userLIST = userLISTService.selectByUserId(userId);
			
			orderInfo.setUserName(userLIST.getUserName());
			orderInfo.setUserContact(userLIST.getUserNo());
			//是否已支付
			orderInfo.setRegisterPayFlag(Constant.CONSTANTS_IS_PAYMENT_FALSE);
			
			//日志表
			//非首儿送药功能，需要查询病人情况
			if (req.getOrderType()!=Constant.CONSTANTS_ORDER_TYPE_ID_4.intValue()) {
				
				PatientList patient=patientListService.selectByPatientId(patientId);
				if(null!=patient)
				{
					orderInfo.setPatientName(patient.getPatientName());
				}else{
					_resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
					_resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);
					return _resp;
				}
			}else{
				
				RegisterOrderExample temp = new RegisterOrderExample();
				List<Integer> runstatusids = new ArrayList<Integer>();
				runstatusids.add(2);       //未接单
				runstatusids.add(3);       //已接单未结束
				temp.setUserid(userId);
				temp.setRunstatusids(runstatusids);
				temp.setRegistertypeid(req.getOrderType());
				temp.setRegisterguideid(String.valueOf(req.getChannel()));
				List<RegisterOrder> orderListNoClosed =  registerOrderService.selectSimple(temp);
				
				if (orderListNoClosed.size()>0) {
					//未结束的首儿送药订单返回接口
					_resp.setOrderInfo(packageRegisterOrderTemp(orderListNoClosed.get(0)));
					_resp.setErrorCode(ResultCode.OPERATION_SUCCESS);
					_resp.setErrorMsg(ResultCode.OPERATION_SUCCESS_NOTE);
					
					//有未结束的首儿送药
					//String[] userIds = {String.valueOf(userId)};
					//rongService.PublishSystemOrderToDocMsgNoChannel(orderListNoClosed.get(0));
					return _resp;
				}
			}
			GoodsPriceListTemp goodsPrice =new GoodsPriceListTemp();;
			//免费校验参数
			if (req.getFreeType()==Constant.CONSTANTS_ORDER_FREE_ID_0.intValue()) {
 
				//免费图文咨询  跳过待支付状态
				orderInfo.setRegisterTotal(new BigDecimal("0"));
				orderInfo.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_2);
				orderInfo.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_2);
				orderInfo.setGoodsid(Long.valueOf(Constant.CONSTANTS_ORDER_FREE_GOODSID));
			}
			else
			{
				
				//图文咨询快问快答
				if (req.getChannel()==Constant.CONSTANTS_ORDER_CHANNEL_ID_7.intValue()) {
					
					//免费
					 if (Constant.CONSTANTS_FREE_PROVICE_NAME.equals(JudeMobileAttribution.getMobileAttribution(userLIST.getUserNo()))) {
							orderInfo.setRegisterTotal(new BigDecimal(0));
					 }else{
							//公共价格信息
							GoodsPriceList queryGoodsPrice = new GoodsPriceList();
							queryGoodsPrice.setGoodsid(Integer.valueOf(req.getGoodsId()));
							goodsPrice=goodsPriceListService.selectByGoodsIdDocId(queryGoodsPrice);
							//患者付费
							orderInfo.setRegisterTotal(new BigDecimal( goodsPrice.getPrice()));
					 }
			
					
				}else if (req.getTreatDocId()==0||StringUtils.isEmpty(req.getGoodsId())) {
					//校验医生入参 报错
					_resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
					_resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);
					return _resp;
				}else
				{
					//医生价格信息 
					GoodsPriceList queryGoodsPrice = new GoodsPriceList();
					queryGoodsPrice.setSerialIdno(req.getTreatDocId().toString());
					queryGoodsPrice.setGoodsid(Integer.valueOf(req.getGoodsId()));
					goodsPrice=goodsPriceListService.selectByGoodsIdDocId(queryGoodsPrice);
					
				    if(null!=goodsPrice.getPrice() )
				    { 
						//患者付费
						orderInfo.setRegisterTotal(new BigDecimal( goodsPrice.getPrice()));
						//医生收费
						orderInfo.setRegisterPayoffTotal(new BigDecimal( goodsPrice.getPrice00()));
				    }else{
				    	//医生未开放服务    报错
				    	_resp.setErrorCode(ResultCode.OPERATION_UN_SUPPORT_ERROR);
						_resp.setErrorMsg(ResultCode.OPERATION_UN_SUPPORT_ERROR_NOTE);
						return _resp;
				    }
				    //免费
				    if (Constant.CONSTANTS_FREE_PROVICE_NAME.equals(JudeMobileAttribution.getMobileAttribution(userLIST.getUserNo()))) {
						orderInfo.setRegisterTotal(new BigDecimal(0));
				    }
					//医生个人信息
					orderInfo.setDepartmentid(req.getDepartmentId());
					orderInfo.setDepartmentName(req.getDepartmentName());
					orderInfo.setAccepterid(req.getTreatDocId());
					orderInfo.setAccepterName(req.getTreatDocName());
					
					StuffDetailDto stuffDetail = stuffListService. selectByStuffId(req.getTreatDocId());
					
					//添加客服信息，StuffAlias,Measure 客服id。
					if (StringUtils.isNotEmpty(stuffDetail.getStuffAlias())) {
						orderInfo.setSsMeasure(stuffDetail.getStuffAlias());
						orderInfo.setRegisterDesc(stuffDetail.getStuffName()+"医师|"+orderInfo.getRegisterDesc());
					}
				}
				
				if (orderInfo.getRegisterTotal().compareTo(new BigDecimal(0))>0) {
					  //订单状态	
					   orderInfo.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_1);
					   orderInfo.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_1);
				}else{
					orderInfo.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_2);
					   orderInfo.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_2);
					
				}
			 
			   //订单编号
			   orderInfo.setGoodsid(Long.valueOf(req.getGoodsId()));
			   
			   
			   //视屏咨询相关参数包装
				if (req.getOrderType()==Constant.CONSTANTS_ORDER_TYPE_ID_3.intValue()) {
			
					orderInfo.setOrderLeftTime(goodsPrice.getChargeQuantity());
					orderInfo.setOrderBillTime(goodsPrice.getChargeQuantity());
					//视屏时间节点
					//预约类必传参数
					if (0==req.getOrderTimeSolt()||null==req.getScheduleTime()) {
						_resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
						_resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);
						return _resp;
					}else{
					//预约信息	
					orderInfo.setComment(String.valueOf(req.getOrderTimeSolt()));
					orderInfo.setScheduleDuration(goodsPrice.getChargeQuantity().intValue()/60);
					orderInfo.setScheduleTime(DateUtils.parseDatetime(req.getScheduleTime(), "yyyy-MM-dd HH:mm"));
					}
				}
			}
			
			
			orderInfo.setGoodsQuantity(new BigDecimal("1"));
			Date currDateTime=DateUtils.getDatetime();
			
			//第一次生成订单，更新时间和创建时间一致
			orderInfo.setCreateDate(currDateTime);
			orderInfo.setUpdateDate(currDateTime);
			//病历数据包装
			MedicalTreatRecordWithBLOBs patRecord = new MedicalTreatRecordWithBLOBs();
			patRecord.setBillNo(DateUtils.todayDate()+"-H"+req.getHospitalId()+"P"+req.getPatId()+"-");
			patRecord.setUserid(userId);
			patRecord.setPatientid(req.getPatId());
			patRecord.setHospitalid(Long.valueOf(req.getHospitalId()));
			patRecord.setDepartmentid(Long.valueOf(req.getDepartmentId()));
			patRecord.setDepartmentName(req.getDepartmentName());
			if(StringUtils.isNotBlank(req.getScheduleTime())){
				patRecord.setScheduleTime(DateUtils.parseDatetime(req.getScheduleTime(), "yyyy-MM-dd HH:mm"));
			}
			patRecord.setPatientDescribe(req.getPatDescribe());
			patRecord.setPatpage1(req.getPatPage1());
			patRecord.setPatpage2(req.getPatPage2());
			patRecord.setPatpage3(req.getPatPage3());
			patRecord.setPatpage4(req.getPatPage4());
			patRecord.setPatpage5(req.getPatPage5());
			patRecord.setPatpage6(req.getPatPage6());
			patRecord.setDoctorid(req.getTreatDocId());
			patRecord.setDoctorName(req.getTreatDocName());
			//记录更新人的姓名
			patRecord.setUpdateUserid(userId);
 
			//返回参数
			RegisterOrderExample temp = registerOrderService.insertOrder(orderInfo, patRecord);
			
			//订单约满
			if (temp.getUpdateNum()==Constant.Schedule_Flag) {
				_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3008);
				_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3008_NOTE);
				return _resp;
			}
			
			//包装返回参数 主要未订单号，订单状态
			RegisterOrderTemp returnOrderInfo = new RegisterOrderTemp();
			returnOrderInfo.setOrderId(String.valueOf(temp.getRegisterid()));
			returnOrderInfo.setOrderState(String.valueOf(orderInfo.getRunstatusid()));
		    MedicalTreatRecordTemp returnPatRecord = new MedicalTreatRecordTemp();
		    returnPatRecord.setPatRecordId(String.valueOf(temp.getRefbillid()));
		    returnOrderInfo.setPatRecord(returnPatRecord);
		    returnOrderInfo.setOrderFee((orderInfo.getRegisterTotal())==null?"0":String.valueOf(orderInfo.getRegisterTotal()));
			_resp.setOrderInfo(returnOrderInfo);
			
			orderInfo.setRegisterid(temp.getRegisterid());
			
			//rongService
			if(orderInfo.getRunstatusid()==Constant.CONSTANTS_ORDER_RUNSTATUS_ID_2.intValue()){
			
				String groupId = String.valueOf(temp.getRegisterid());
				String[] userIds = {String.valueOf(userId)};
				rongService.createGroup(userIds, groupId, groupId);
				rongService.PublishSystemOrderToDocMsg(orderInfo);
				
				//判断是否有客服
				if (StringUtils.isNotEmpty(orderInfo.getSsMeasure())) {
					String[] assisIds = {orderInfo.getSsMeasure()};
					rongService.joinGroup(assisIds, groupId, groupId);
					rongService.PublishSystemOrderToAssisMsg(String.valueOf(userId),orderInfo.getSsMeasure(), groupId);
				}
			}
		}
		
		_resp.setErrorCode(ResultCode.OPERATION_SUCCESS);
		_resp.setErrorMsg(ResultCode.OPERATION_SUCCESS_NOTE);
 
		return _resp;
	}
	
	 
	/**
	 * 线程启动
	 * @author HiRoad
	 *
	 */
	private class delayPublishGroupMsg extends Thread
	 {
		private IRongService rongService;
		private RegisterOrder registerOrder; 
		
	     public delayPublishGroupMsg(  IRongService rongService,RegisterOrder registerOrder ) {
			super();
		;
			this.rongService = rongService;
			this.registerOrder=registerOrder;
		}

		public void run()
	     {
			 try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			 rongService.PublishGroupMsg(registerOrder);
	     }
	 }
	
	private RegisterOrderTemp packageRegisterOrderTemp(RegisterOrder order){
		
		RegisterOrderTemp curr =new RegisterOrderTemp();
		curr.setContactTel(order.getUserContact());
		curr.setCreateTime(DateUtils.formatDatetime(order.getCreateDate()));
		//doctor transfer
		curr.setDoctor(order.getDoctor());
		curr.setFreeType(String.valueOf(order.getOrderfeetypeid()));
		curr.setOrderFee((order.getRegisterTotal())==null?"0":String.valueOf(order.getRegisterTotal()));
		curr.setOrderId(String.valueOf(order.getRegisterid()));
		curr.setOrderNumber(order.getRegisterNo());
		curr.setOrderState(String.valueOf(order.getRunstatusid()));
		curr.setOrderType(String.valueOf(order.getRegistertypeid()));
		
		//patient Record transfer
		curr.setPayType(String.valueOf(order.getPayTypeId()));
		
		curr.setUpdateTime((order.getUpdateDate())==null?null:DateUtils.formatDatetime(order.getUpdateDate()));
		curr.setScheduleTime((order.getScheduleTime())==null?null:DateUtils.formatDatetime(order.getScheduleTime()));
		//user transfer
		curr.setUser(order.getUser());
		curr.setPatRecord(order.getPatRecord());
		curr.setDoctor(order.getDoctor());
			
		curr.setOrderTime((order.getScheduleDuration())==null?"0":String.valueOf(order.getScheduleDuration()));
		
		
		curr.setUserId(String.valueOf(order.getUserid()));
		curr.setPatId(String.valueOf(order.getPatientid()));
		curr.setPatRecordId(null);
		curr.setPatDescribe(order.getRegisterDesc());
		curr.setGoodsIdNo(order.getGoodsIdno());
		curr.setGoodsName(order.getGoodsName());
		curr.setChannel(String.valueOf((order.getRegisterguideid())));

		PatientListTemp patient = new PatientListTemp();
		patient.setPatName(order.getUser().getUserName());
		curr.setPatient(patient);
			
		return  curr;
	}

	public IRegisterOrderService getRegisterOrderService() {
		return registerOrderService;
	}


	public void setRegisterOrderService(IRegisterOrderService registerOrderService) {
		this.registerOrderService = registerOrderService;
	}


	public IUserLISTService getUserLISTService() {
		return userLISTService;
	}


	public void setUserLISTService(IUserLISTService userLISTService) {
		this.userLISTService = userLISTService;
	}


	public IPatientListService getPatientListService() {
		return patientListService;
	}


	public void setPatientListService(IPatientListService patientListService) {
		this.patientListService = patientListService;
	}


	public IGoodsPriceListService getGoodsPriceListService() {
		return goodsPriceListService;
	}


	public void setGoodsPriceListService(
			IGoodsPriceListService goodsPriceListService) {
		this.goodsPriceListService = goodsPriceListService;
	}


	public IRongService getRongService() {
		return rongService;
	}


	public void setRongService(IRongService rongService) {
		this.rongService = rongService;
	}


	public IStuffListService getStuffListService() {
		return stuffListService;
	}


	public void setStuffListService(IStuffListService stuffListService) {
		this.stuffListService = stuffListService;
	}
	
	
	
}
